package com.example.student.service.impl;

import com.example.student.constant.ResultCode;
import com.example.student.dao.StudentDAO;
import com.example.student.entity.ResultDO;
import com.example.student.entity.StudentDO;
import com.example.student.service.StudentInterService;
import com.example.student.util.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 学生逻辑实现
 *
 * @author
 */
@ComponentScan({"com.example.student.dao"})
@Service("studentService")
public class StudentServiceImpl implements StudentInterService {

    @Resource
    private StudentDAO studentDAO;

    @Override
    public ResultDO<PageUtils<StudentDO>> getStudent(Map<String, Object> params) {
        List<StudentDO> result = studentDAO.getStudent(params);
        if (result == null) {
            return new ResultDO<>(false, ResultCode.DB_ERROR, ResultCode.MSG_DB_ERROR, null);
        }

        return new ResultDO<>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS, new PageUtils<>(studentDAO.count(params), result));
    }

    @Override
    public ResultDO<Void> insert(StudentDO studentDO) {
        if (StringUtils.isBlank(studentDO.getName())) {
            return new ResultDO<>(false, ResultCode.PARAMETER_INVALID, ResultCode.MSG_PARAMETER_INVALID, null);
        }

        try {
            studentDAO.insert(studentDO);
        } catch (Exception e) {
            return new ResultDO<>(false, ResultCode.DB_ERROR, ResultCode.MSG_DB_ERROR, null);
        }

        return new ResultDO<>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS, null);
    }

    @Override
    public ResultDO<Void> delete(String id) {
        if (StringUtils.isBlank(id)) {
            return new ResultDO<>(false, ResultCode.PARAMETER_INVALID, ResultCode.MSG_PARAMETER_INVALID, null);
        }

        try {
            studentDAO.delete(id);
        } catch (Exception e) {
            return new ResultDO<>(false, ResultCode.DB_ERROR, ResultCode.MSG_DB_ERROR, null);
        }

        return new ResultDO<>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS, null);
    }

    @Override
    public ResultDO<Void> update(StudentDO studentDO) {
        if (StringUtils.isBlank(studentDO.getId()) || StringUtils.isBlank(studentDO.getName())) {
            return new ResultDO<>(false, ResultCode.PARAMETER_INVALID, ResultCode.MSG_PARAMETER_INVALID, null);
        }

        try {
            studentDAO.update(studentDO);
        } catch (Exception e) {
            return new ResultDO<>(false, ResultCode.DB_ERROR, ResultCode.MSG_DB_ERROR, null);
        }

        return new ResultDO<>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS, null);
    }

}
